package net.pulseproject.commons.midi;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;

import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiDevice.Info;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.inject.Inject;

public class MidiDeviceCacheImpl implements MidiDeviceCache {

	private static final Log LOG = LogFactory.getLog(MidiDeviceCacheImpl.class);
	
	private final MidiSystem midiSystem;
	
//	private final PreferencesStore preferences;
	
	private Collection<MidiDevice> cachedMidiDevices;
	
	
	@Inject
	public MidiDeviceCacheImpl(final MidiSystem midiSystem) {
		LOG.info("new MidiDeviceCacheImpl(midiSystem)");
		this.midiSystem = midiSystem;
//		this.preferences = preferences;
	}
	
	@Override
	public final synchronized Collection<MidiDevice> fetchMidiDevices() {
		LOG.debug("fetchMidiDevices()");
		this.checkCache();
		return this.cachedMidiDevices;
	}
	
	private void checkCache() {
		if(this.cachedMidiDevices == null) {
			this.loadCache();
		}
	}
	
	private void loadCache() {
		LOG.debug("loadCache()");
		final Info[] infos = this.midiSystem.listMidiDeviceInfos();
		final Collection<MidiDevice> foundDevices = new HashSet<MidiDevice>(infos.length);
		
//		final String portFilter = this.preferences.get(PreferencesField.PORT_FILTER);
//		final String[] portFilterRegExps = StringUtil.splitAndTrimElements(portFilter, ",");
		
		for (final Info info : infos) {
//			if(portFilterRegExps.length == 0 || StringUtil.matchesRegExps(info.getName(), portFilterRegExps) == true) {
			final MidiDevice midiDevice = this.midiSystem.getMidiDevice(info);
			foundDevices.add(midiDevice);
//			}
		}
		
		this.cachedMidiDevices = Collections.unmodifiableCollection(foundDevices);
	}
}
